#import "SettingViewController.h"
#import "UMFeedback.h"
#import "UpdateManager.h"
#import "FeedbackViewController.h"
#import "UserManager.h"
#import "LoginViewController.h"
#import "AboutViewController.h"
#import "GridViewCellDemo.h"
#import "UMTableViewController.h"
#import "NetWorkManager.h"
#import "DBManager.h"
#import "DataCacheManager.h"
#import "DBManager.h"
#import "SDImageCache.h"
#import "CoreDataManager.h"

@implementation SettingViewController

static int NUMBER_OF_COLUMNS = 4;
static int NUMBER_OF_APPS_PERPAGE = 8;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    PP_RELEASE(_mGridView);
    PP_RELEASE(moreApps);
    PP_RELEASE(feedBack);
    PP_RELEASE(newVersion);
    PP_RELEASE(listData);
    PP_RELEASE(seperateLine);
    PP_RELEASE(loginAndRegisterBtn);
    PP_RELEASE(appsRecommendText);
    PP_RELEASE(clearCache);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    baseTitle.text = @"设置";

    self.navigationController.view.layer.cornerRadius = 4;
    self.navigationController.view.layer.masksToBounds = YES;
    self.navigationController.navigationBar.layer.cornerRadius = 4;
    self.navigationController.navigationBar.layer.masksToBounds = YES;
    
    UIButton* menuBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_1.png"] forState:UIControlStateNormal];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_2.png"] forState:UIControlStateHighlighted];
    [menuBtn addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menuBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:menuBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:menuBarBtn];
    
    feedBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 280, 40)];
    
    newVersion = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 280, 40)];
    
    listData = [[NSArray alloc] initWithObjects:@"意见反馈", @"检测新版本", nil];
    
    UIImage *seperateLineBackgournd = [[UIImage imageNamed:@"post_full_line.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];
    seperateLine.image = seperateLineBackgournd;
    
    //    _mGridView = [[UMUFPGridView alloc] initWithFrame:CGRectMake(0, 150, 320, 330) appkey:@"502b550252701547f800003a" slotId:nil currentViewController:self];
    _mGridView = [[UMUFPGridView alloc] initWithFrame:CGRectMake(0, appsRecommendText.frame.origin.y+appsRecommendText.frame.size.height +12, self.view.frame.size.width, 180) appkey:UMENG_APPKEY slotId:nil currentViewController:self];

    _mGridView.backgroundColor = [UIColor clearColor];
//    _mGridView.datasource = self;
//    _mGridView.delegate = self;
    _mGridView.mAutoFill= NO;
    _mGridView.dataLoadDelegate = self;
    _mGridView.mDataLoder = NO;  //设置是否自动加载推荐的app应用
    _mGridView.autoresizesSubviews = YES;
    _mGridView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
//    [_mGridView requestPromoterDataInBackground];
    
    // ----暂时不上应用推荐
    [self.view addSubview:_mGridView];
    
    UIImage *btnMiddleOne= [[UIImage imageNamed:@"post_camera_1.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:21];
    UIImage *btnMiddleTwo = [[UIImage imageNamed:@"post_camera_2.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:21];

    [moreApps setBackgroundImage:btnMiddleOne forState:UIControlStateNormal];
    [moreApps setBackgroundImage:btnMiddleTwo forState:UIControlStateHighlighted];
    moreApps.titleLabel.textAlignment = UITextAlignmentCenter;
    
    moreApps.hidden = YES;
    appsRecommendText.hidden = YES;
    _mGridView.hidden = YES;
    
    [self getSizeOfDisk];
}

- (void)viewDidUnload {
    PP_RELEASE(_mGridView);
    PP_RELEASE(moreApps);
    PP_RELEASE(feedBack);
    PP_RELEASE(newVersion);
    PP_RELEASE(listData);
    PP_RELEASE(seperateLine);
    PP_RELEASE(loginAndRegisterBtn);
    PP_RELEASE(appsRecommendText);
    PP_RELEASE(clearCache);
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated {
    CGRect moreAppsFrame = moreApps.frame;
    moreAppsFrame.origin.y = _mGridView.frame.origin.y+_mGridView.frame.size.height;
    moreApps.frame = moreAppsFrame;
}

- (void)viewWillAppear:(BOOL)animated {
    [self changeLoginAndLogoutText];
}

#pragma mark -
#pragma mark -------GridViewDelegate 协议方法-------

//(可选)GridView中indexPath处item被点击后触发
-(void)gridView:(UMUFPGridView *)gridView didSelectRowAtIndexPath:(IndexPath *)indexPath {
    Log(@"MARK");
}
//(可选)GridView中Item的高度，默认是 80.0f
-(CGFloat)gridView:(UMUFPGridView *)gridView heightForRowAtIndexPath:(IndexPath *)indexPath {
    return 80.0f;
}

#pragma mark -
#pragma mark -------GridViewDataSource 协议方法-------
//【必须】每页的列数，如横屏返回5, 竖屏返回3
- (NSInteger)numberOfColumsInGridView:(UMUFPGridView *)gridView {
    return NUMBER_OF_COLUMNS;
}
//(可选)每页最多显示多少app
- (NSInteger)numberOfAppsPerPage:(UMUFPGridView *)gridView {
    return NUMBER_OF_APPS_PERPAGE;
}
//【必须】GridView中indexPath处的Item，有复用机制
-(UIView *)gridView:(UMUFPGridView *)gridView cellForRowAtIndexPath:(IndexPath *)indexPath {
    GridViewCellDemo *view = [[[GridViewCellDemo alloc] initWithIdentifier:nil] autorelease];
    return view;
}
//【必须】GridView中indexPath处的Item的具体内容
-(void)gridView:(UMUFPGridView *)gridView relayoutCellSubview:(UIView *)view withIndexPath:(IndexPath *)indexPath {
    int arrIndex = [gridView arrayIndexForIndexPath:indexPath];
    if (arrIndex < [_mGridView.mPromoterDatas count])
    {
        NSDictionary *promoter = [_mGridView.mPromoterDatas objectAtIndex:arrIndex];
        GridViewCellDemo *imageViewCell = (GridViewCellDemo *)view;
        imageViewCell.indexPath = indexPath;
        imageViewCell.titleLabel.text = [promoter valueForKey:@"title"];
        [imageViewCell.imageView setImageURL:[NSURL URLWithString:[promoter valueForKey:@"icon"]]];
    }
}

#pragma mark -
#pragma mark -------GridViewDataLoadDelegate 协议方法-------

//(可选)在广告数据获取后会被调用 【注：广告数据获取成功后，reloadData方法会被自动调用】
-(void)UMUFPGridViewDidLoadDataFinish:(UMUFPGridView *)gridView promotersAmount:(NSInteger)promotersAmount {
//    Log(@"MARK");
//    Log(@"%d", promotersAmount);
//    Log(@"gridView.mPromoterDatas :%@", gridView.mPromoterDatas);

    [gridView reloadData];
}
//(可选)广告获取失败后被调用
-(void)UMUFPGridView:(UMUFPGridView *)gridView didLoadDataFailWithError:(NSError *)error {
//    Log(@"MARK");
}

- (void)changeLoginAndLogoutText {
    if ([UserManager sharedInstance].isLogin) {
        Log(@"已登录");
        [loginAndRegisterBtn setTitle:@"退出" forState:UIControlStateNormal];
        loginAndRegisterBtn.titleLabel.textAlignment = UITextAlignmentCenter;
        [loginAndRegisterBtn addTarget:self action:@selector(quitLogin) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
//
//- (IBAction)mainSite:(id)sender {
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.lengxiaohua.com"]];
//}
//
//- (IBAction)sinaWeibo:(id)sender {
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://weibo.com/lengxiaohua"]];
//}
//
//- (IBAction)tengxunWeibo:(id)sender {
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://t.qq.com/leng-xiao-hua"]];
//}
//
//- (IBAction)email:(id)sender {
//    [self sendMailInApp];//调用sendMailInApp方法，弹出新的view
//}

- (void)showMenu
{
    if ([self respondsToSelector:@selector(presentingViewController)]) {        
        if (self.presentedViewController) {
            [[self presentedViewController] dismissModalViewControllerAnimated:YES];
        }
        else {
            [self dismissModalViewControllerAnimated:YES];
        }
    }
    else {
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
    }
}



//#pragma mark -
//#pragma mark - 在应用内发送邮件
////激活邮件功能
//- (void)sendMailInApp
//{
//    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
//    if (!mailClass) {
//        [self alertWithMessage:@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替"];
//        return;
//    }
//    if (![mailClass canSendMail]) {
//        [self alertWithMessage:@"用户没有设置邮件账户"];
//        return;
//    }
//    [self displayMailPicker];
//}

//调出邮件发送窗口
//- (void)displayMailPicker
//{
//    MFMailComposeViewController *mailPicker = [[MFMailComposeViewController alloc] init];
//    mailPicker.mailComposeDelegate = self;
//    
//    //设置主题
//    [mailPicker setSubject: @"冷笑话反馈"];
//    //添加收件人
//    NSArray *toRecipients = [NSArray arrayWithObject: @"support@lengxiaohua.com"];
//    [mailPicker setToRecipients: toRecipients];
//    //    //添加抄送
//    //    NSArray *ccRecipients = [NSArray arrayWithObjects:@"second@example.com", @"third@example.com", nil];
//    //    [mailPicker setCcRecipients:ccRecipients];
//    
//    NSString *emailBody = @"<font color='red'>内容：</font> ";
//    [mailPicker setMessageBody:emailBody isHTML:YES];
//    [self presentModalViewController: mailPicker animated:YES];
//    [mailPicker release];
//}
//
//
//#pragma mark - 实现 MFMailComposeViewControllerDelegate
//- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
//{
//    //关闭邮件发送窗口
//    [self dismissModalViewControllerAnimated:YES];
//    NSString *msg;
//    switch (result) {
//        case MFMailComposeResultCancelled:
//            msg = @"用户取消编辑邮件";
//            break;
//        case MFMailComposeResultSaved:
//            msg = @"用户成功保存邮件";
//            break;
//        case MFMailComposeResultSent:
//            msg = @"用户点击发送，将邮件放到队列中，还没发送";
//            break;
//        case MFMailComposeResultFailed:
//            msg = @"用户试图保存或者发送邮件失败";
//            break;
//        default:
//            msg = @"";
//            break;
//    }
//    [self alertWithMessage:msg];
//}

- (void)alertWithMessage:(NSString*)message
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil
                                                   message:message
                                                  delegate:nil
                                         cancelButtonTitle:@"确定"
                                         otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}

- (void)quitLogin {
    [[UserManager sharedInstance] logout];
}

-(void) back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//#pragma mark - Table view data source
//
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return 35;
//}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return 1;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    return 2;
//}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    static NSString *CellIdentifier = @"Cell";
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//    if (cell == nil) {
//        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//    }
//    NSUInteger row = [indexPath row];
//    cell.textLabel.text = [listData objectAtIndex:row];
//    cell.textLabel.textAlignment = UITextAlignmentCenter;
//    return cell;
//}
//
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSUInteger row = [indexPath row];
//    if (indexPath.section == 0 && row == 0) {
//        FeedbackViewController *feedbackController = [[FeedbackViewController alloc] initWithNibName:@"FeedbackViewController" bundle:nil];
//        [self.navigationController pushViewController:feedbackController animated:YES];
//    }
//    
//    if (indexPath.section == 0 && row == 1) {
//        UpdateManager *tUpdateManager = [UpdateManager sharedInstance];
//        [tUpdateManager checkVersion:YES];//调用线程更新方法
//    }
//    
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//}


- (IBAction)goLoginAndRegister:(id)sender {
    if (![UserManager sharedInstance].isLogin) {
        LoginViewController *login = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
        [self.navigationController pushViewController:login animated:YES];
        //这里 login不能release,否则会崩溃
    }else{
        [self baseShowInfoHud:NSLocalizedString(@"退出成功", @"") andIsTop:NO];
        [loginAndRegisterBtn setTitle:@"登录注册" forState:UIControlStateNormal];
    }
    
//    [login release];
}

- (IBAction)goCheckNewVersion:(id)sender {
    HAS_NO_NETWORK(self);
    UpdateManager *tUpdateManager = [UpdateManager sharedInstance];
    [tUpdateManager checkVersion:YES :self];//调用线程更新方法
}

- (IBAction)goAbout:(id)sender {
    AboutViewController *about = [[AboutViewController alloc]initWithNibName:@"AboutViewController" bundle:nil];
    [self.navigationController pushViewController:about animated:YES];
    [about release];
}

- (IBAction)goFeedback:(id)sender {
    FeedbackViewController *feedback = [[FeedbackViewController alloc] initWithNibName:@"FeedbackViewController" bundle:nil];
    [self.navigationController pushViewController:feedback animated:YES];
    [feedback release];
}

- (IBAction)goMoreApps:(id)sender {
    UMTableViewController *controller = [[UMTableViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

- (IBAction)goClearCache:(id)sender {
    Log(@"clear cache start");
 
//    [[DataCacheManager sharedInstance].jokeManagerAll clearJokeData];
//    [[DataCacheManager sharedInstance].jokeManagerHot clearJokeData];
//    [[DataCacheManager sharedInstance].jokeManagerShit clearJokeData];
//    [[DataCacheManager sharedInstance].topicManagerAll clearTopicData];
//    [[DBManager sharedInstance] clearAllData];

    [[SDImageCache sharedImageCache]clearDisk]; //清除硬盘的内容
    [[CoreDataManager sharedInstance]coredataTopicDetailPathDictUpdate]; //清除coredata里所有笑话dictPath内容

    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateCoredata" object:self];
}

- (void)getSizeOfDisk{
    int size = [[SDImageCache sharedImageCache]getSize];
    float sizeForMB = roundf(size);
    NSLog(@"%f-----多少mb:%fMB",sizeForMB,sizeForMB/(1024*1024));
    [clearCache setTitle:[NSString stringWithFormat:@"%fMB",sizeForMB/(1024*1024)] forState:UIControlStateNormal];
}

- (void)clearTheCache{
    [[SDImageCache sharedImageCache]clearDisk];
}

- (void)clearData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = nil;
    
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        hud.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
        hud.mode = MBProgressHUDModeCustomView;
        
        sleep(0.8f);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            
        });
    });
}

@end

